<?php

namespace mybackend\controllers;

use common\error\ErrorCode;
use common\services\myhtsq\ErpUserService;
use common\support\VerfCodeManage;
use Yii;
use yii\filters\AccessControl;
use common\services\myhtsq\ErpInterfaceService;
use common\services\myhtsq\RoleService;
use common\support\StringHelper;
use common\support\UserAgentHelper;
use linslin\yii2\curl\Curl;
use yii\helpers\ArrayHelper;
use yii\web\Response;

/**
 * Site controller
 */
class SiteController extends BaseController {


    public function __construct($id, $module, $config = []) {
        parent::__construct($id, $module, $config);
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'login-data', 'error', 'verf-code', 'query-test','clear-cache', 'get-auth-actions','get-online-service-url'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'clear-cache'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'common\actions\SystemError',
            ],
        ];
    }

    /**
     * @desc 跳转首页
     * @method get
     * @return type
     */
    public function actionIndex() {
        if (isset(Yii::$app->params["root-page"])) {
            return $this->redirect(Yii::$app->params["root-page"]);
        } else {
            return $this->render("index");
        }
    }

    /**
     * @desc 按模块获取验证码。登录模块为login
     * @method get
     * @param $module
     */
    public function actionVerfCode($module) {
        VerfCodeManage::responseVerfCode($module);
    }

    /**
     * @desc 登录提交操作
     * @method post
     * @body usercode=&password=&verfcode=
     * @return type
     */
    public function actionLogin($kfs='') {
        $usercode = isset($_POST["usercode"]) ? $_POST["usercode"] : '';
        $password = isset($_POST["password"]) ? $_POST["password"] : '';
        $verfcode = isset($_POST["verfcode"]) ? $_POST["verfcode"] : '';

        if (!VerfCodeManage::validVerfCode("login", $verfcode)) {
            $error = "验证码输入错误！";
            if ($this->isAjaxRequest()) {
                return $this->json(array(
                            "retCode" => '-1',
                            "errMsg" => $error
                ));
            } else {
                return $this->toLoginPage(['error' => $error, 'kfs' => $kfs]);
            }
        }
        $result = ErpInterfaceService::getUserByCodeAndPassword($usercode, $password);

        $error = '';
        if (is_null($result)) {
            $error = "账号或者密码不正确";
        } else if ($result->IsDisabeld) {
            $error = "您的用户已经被禁用";
        }

        if (!empty($error)) {
            if ($this->isAjaxRequest()) {
                return $this->json(array(
                            "retCode" => '-1',
                            "errMsg" => $error
                ));
            } else {
                return $this->toLoginPage(['error' => $error]);
            }
        }
        
        call_user_func(Yii::$app->user->identityClass . "::clearCache", $usercode);
        $user = call_user_func(Yii::$app->user->identityClass . "::findIdentity", $usercode);
        Yii::$app->user->login($user);

        if ($this->isAjaxRequest()) {
            return $this->json(array(
                        "retCode" => ErrorCode::SUCCESS,
            ));
        } else {
            return $this->goBack(Yii::$app->getHomeUrl());
        }
    }

    /**
     * 跳转登录页
     * @param type $parameters
     * @return boolean
     */
    public function toLoginPage($parameters = []) {
        $page = '/login.html';
        if (isset(Yii::$app->params["login-page"])) {
            $page = Yii::$app->params["login-page"];
        }
        if (count($parameters) == 0) {
            Yii::$app->getResponse()->redirect($page);
        } else {
            $paraArr = [];
            foreach ($parameters as $key => $item) {
                $paraArr[] = $key . '=' . urlencode($item);
            }
            Yii::$app->getResponse()->redirect($page . '?' . join("&", $paraArr));
        }
        Yii::$app->end();
        return true;
    }

    /*
     *
     * Author yuyj
     * Date 2017-01-07
     * @apiVersion 1.0.0
     * @api {get} /api/index.php/site/login-data 获取登陆用户信息
     * @apiGroup site-controller
     *
     * @apiResponse 200 {"retCode":"0","data":{"isGuest":false,"userName":"余云建","userGuid":"814eddb3-832e-e511-9b71-848f69dfab18","buGuid":"68af85a3-c5ee-4626-a00e-3a7efe8a86cc","buName":"深圳市明源云客电子商务有限公司","departmentGuid":"8bae1df8-0bc6-e411-aad8-848f69dfab18","departmentName":"研发部","areaRole":false}}
     */
    public function actionLoginData()
    {
        $data = [
            "isGuest"  => Yii::$app->user->isGuest,
            "userName" => Yii::$app->user->isGuest ? "" : Yii::$app->user->identity->username,
            "userGuid" => Yii::$app->user->isGuest ? "" : Yii::$app->user->identity->userguid,
            "buGuid" => Yii::$app->user->identity->buGuid,
            "buName" => Yii::$app->user->identity->buName,
            "departmentGuid" => Yii::$app->user->identity->departmentGuid,
            "departmentName" => Yii::$app->user->identity->departmentName,
            "areaRole" => Yii::$app->user->isGuest ? true : RoleService::isAreaRole(Yii::$app->user->identity->userguid),
        ];

        /** @var  $roleService RoleService*/
        $roleService = \Yii::createObject(RoleService::className());

        $data['isAreaCharge'] = 0;
        if ($data['userGuid']) {
            $data['isAreaCharge'] = $roleService->isAreaAuthRole(Yii::$app->user->identity->userguid);
        }

        return $this->json([
            "retCode" => ErrorCode::SUCCESS,
            "data"    => $data,
        ]);
    }

    /**
     * @desc 注销
     * @method post
     */
    public function actionLogout() {
        //先清除缓存
        $usercode = Yii::$app->user->identity->usercode;
        call_user_func(Yii::$app->user->identityClass . "::clearCache", $usercode);

        Yii::$app->user->logout();

        if ($this->isAjaxRequest()) {
            return $this->json(array(
                        "retCode" => ErrorCode::SUCCESS,
            ));
        } else {
            return $this->toLoginPage();
        }
    }

    /**
     * @desc 清除缓存
     * @method post
     * @return string
     */
    public function actionClearCache() {
        Yii::$app->cache->flush();
        return $this->json(array(
                    ErrorCode::SUCCESS
        ));
    }   
    
    public function actionGetAuthActions() {
        if (Yii::$app->user->isGuest) {
            return false;
        }
        $auths = RoleService::getAuthCache(Yii::$app->user->identity->userguid);
        $actions = array_values(array_unique($auths));
        return $this->json(array(
                    "retCode" => ErrorCode::SUCCESS,
                    "data" => $actions
        ));
    }
    /**
     * @desc 获取在线客服登录地址
     * @method get
     * @return string
     */
    public function actionGetOnlineServiceUrl()
    {
        $identity = Yii::$app->user->identity;
        $request = Yii::$app->request;
        $metadata = [];
        try {
            $appCode = 'ggmk';
            $tenantId = '39d22ddd-5976-25ba-f91f-f7b355f9ac0d'; //yktyadmin
            if (Yii::$app->user->isGuest) {
                $userName = '未登录访客';
                $userGUID = StringHelper::uuid();
                $metadata['用户角色'] = '未登录访客';
            }else{
                $userName = $identity->username;
                $userGUID = $identity->userguid;
                $metadata['用户角色'] = $identity->buName.'-'.$identity->departmentName;
            }
            $phone = '';
            $env_orgcode = 'yktyadmin';
            $userAgent = UserAgentHelper::parse($request->getHeaders()->get('User-Agent', ''));
            $metadata['客户端'] = '电脑';
            $metadata['操作系统'] = $userAgent['os'];
            $metadata['浏览器'] = $userAgent['webBrower'];
            $metadata = urlencode(json_encode($metadata,JSON_UNESCAPED_UNICODE));
            $curl = new Curl();
            $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
            if (empty($appCfg)) {
                $res = [
                    'retCode' => __LINE__,
                    'data' => [],
                    'retMsg' => "远程接口配置丢失！"
                ];
                return $this->json($res);
            }
            $url = $appCfg['url'] . '?r=online-service/get-login-url&env_orgcode=' . $env_orgcode . '&app_code=' . $appCode . '&tenant_id=' . $tenantId . ($userName != '' ? '&user_name=' . urlencode($userName) : '') . ($phone != '' ? '&phone=' . $phone : '') . ($userGUID != '' ? '&userguid=' . $userGUID : '') . '&metadata=' . $metadata;
            $res = $curl->get($url, true);
            $decRes = json_decode($curl->response, true);
            if ($res === false || !$decRes) {
                $res = [
                    'retCode' => __LINE__,
                    'data' => [],
                    'retMsg' => '调用extapi(' . $appCfg['url'] . ')出错'
                ];
                return $this->json($res);
            }
            $res = [
                'retCode' => isset($decRes['retCode']) ? $decRes['retCode'] : ErrorCode::SUCCESS,
                'data' => isset($decRes['data']) ? ['url' => $decRes['data']] : [],
                'retMsg' => isset($decRes['retMsg']) ? $decRes['retMsg'] : ''
            ];

        } catch (\Exception $e) {
            Yii::info('请求在线客服链接发生异常：' . $e->getMessage());
            $res = [
                'retCode' => __LINE__,
                'data' => [],
                'retMsg' => '请求在线客服链接发生异常!'
            ];
        }
        if (isset($_GET['callback'])) {
            return $this->jsonp($res);
        } else {
            return $this->json($res);
        }
    }
    /**
     * 输出jsonp
     * @param $data array|object 数据
     */
    protected function jsonp($data)
    {
        $callbackFn = $_GET["callback"];
        $dataScript = json_encode($data);
        $script = "{$callbackFn}({$dataScript});";

        return $this->javascript($script);
    }
    /**
     * 输出javascript
     * @param $script
     */
    protected function javascript($script)
    {
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_RAW;
        $response->getHeaders()->set('Content-Type', 'application/javascript; charset=' . $response->charset);
        $response->data = $script;

        return $script;
    }
}
